import {Component} from 'react'
import { Input,InputNumber,Cascader,Upload,Checkbox,Button,message,Tooltip } from 'antd';
import ImgCrop from 'antd-img-crop';
import './management.css';
import axios from 'axios'
import Uploadpic from './Uploadpic'
import {inject,observer} from "mobx-react";

@inject('management')
@observer
class PublishTwo extends Component{
    state={
        fileList:[], //第一个图片数组
        fileList1:[], //第二个图片数组
        options:[], //获取下拉数据
        shopNameValue:'',//商品名字
        typeValue:'',//商品类别二级联动
        numValue:'',  //价格
        numValue1:'',
        numValue2:'',
        sizeValue:'', //规格
        colorValue:'',
        brandValue:'',
        placeValue:'',
        checked:false, //勾选协议
    }


    onChange = ({fileList: newFileList}) => {
        this.setState({
            fileList:newFileList
        })
    };
    beforeUploadMains = () => { // 自定义上传事件
        return false; // 《《= 关键 阻止upload默认上传事件
    }
    onPreview = async file => {
        let src = file.url;
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj);
                reader.onload = () => resolve(reader.result);
            });
        }
        const image = new Image();
        image.src = src;
        const imgWindow = window.open(src);
        imgWindow.document.write(image.outerHTML);
    };
    // 得到输入的值
    // 1、商品名字
    shopName = (e) =>{
        this.setState({
            shopNameValue:e.target.value
        })
    }
    // 3、商品类别二级联动
    onChange2= (value) => {
        this.setState({
            typeValue:value
        })
    }
    // 4、数字输入框--库存
    onChangeNum = (value) => {
        this.setState({
            numValue:value
        })
    }
    onChangeNum1 = (value) => {
        this.setState({
            numValue1:value
        })
    }
    onChangeNum2 = (value) => {
        this.setState({
            numValue2:value
        })
    }
    size = (e) => {
        this.setState({
            sizeValue:e.target.value
        })
    }
    color = (e) => {
        this.setState({
            colorValue:e.target.value
        })
    }
    brand = (e) => {
        this.setState({
            brandValue:e.target.value
        })
    }
    place = (e) => {
        this.setState({
            placeValue:e.target.value
        })
    }
    // 7、多选框(协议)
    onChange3 = (e) => {
        this.setState({
            checked:e.target.checked
        })
    }
    //把获取到二级下拉数据转换成option相同的属性value和label
    getList=(list,newKey,oldKey)=>{
        list.forEach(item=>{
            if(item.children && item.children.length>0){
                item[newKey] = item[oldKey];
                delete item[oldKey];
                this.getList(item.children,newKey,oldKey)
            }else {
                item[newKey] = item[oldKey];
                delete item[oldKey]
            }
        });
        return list;
    }
    erjixiala = () => {
        // 请求下拉列表的数据
        let yiji = []
        axios.post("/api/backstage/shop/findAllGroups").then((res) => {
            //把拿到的扁平数据转化为属性数据
            let data = res.data.data
            for (let i = 0; i < data.length; i++) {
                if (data[i].groupLevel === 1) {
                    yiji.push(data[i])
                }
            }
            for (let i = 0; i < yiji.length; i++) {
                if (!yiji[i].children) {
                    yiji[i].children = []
                }
                for (let j = 0; j < data.length; j++) {
                    if (data[j].groupLevel === 2 && data[j].groupParentId === yiji[i].groupId) {
                        yiji[i].children.push(data[j])
                    }
                }
            }
            yiji = this.getList(yiji,'value','groupId')
            yiji = this.getList(yiji,'label','groupName')
            this.setState({
                options:yiji
            })
        })
    }

    componentDidMount() {
        this.erjixiala()
    }


    publish=()=>{

        if (this.state.checked === true)
        {
            if (this.state.fileList!==undefined && this.props.management.data!==undefined
            && this.state.fileList.length === 6 && this.props.management.data.length === 5){

                if (this.state.shopNameValue!=='' &&
                    this.state.typeValue!=='' &&
                    this.state.numValue!=='' &&
                    this.state.numValue1!=='' &&
                    this.state.numValue2!=='' &&
                    this.state.sizeValue!=='' &&
                    this.state.colorValue!=='' &&
                    this.state.brandValue!=='' &&
                    this.state.placeValue!=='')
                {
                    let formData=new FormData();

                    formData.append('goodsName',this.state.shopNameValue);
                        formData.append('picimgFile1',this.state.fileList[0]?this.state.fileList[0].originFileObj:"");
                        formData.append('picimgFile2',this.state.fileList[1]?this.state.fileList[1].originFileObj:"");
                        formData.append('picimgFile3',this.state.fileList[2]?this.state.fileList[2].originFileObj:"");
                        formData.append('picimgFile4',this.state.fileList[3]?this.state.fileList[3].originFileObj:"");
                        formData.append('picimgFile5',this.state.fileList[4]?this.state.fileList[4].originFileObj:"");
                        formData.append('picimgFile6',this.state.fileList[5]?this.state.fileList[5].originFileObj:"");
                    formData.append('goodsGroupId',this.state.typeValue[1]);
                    formData.append('goodsRealPrice',parseInt(this.state.numValue));
                    formData.append('goodsHighPrice',parseInt(this.state.numValue1));
                    formData.append('goodsNumber',parseInt(this.state.numValue2));
                    formData.append('goodsSize',this.state.sizeValue);
                    formData.append('goodsColor',this.state.colorValue);
                    formData.append('goodsBrand',this.state.brandValue);
                    formData.append('goodsPlace',this.state.placeValue);
                    formData.append('userName',"shop01");
                        formData.append('descimgFile7',this.props.management.data[0]?this.props.management.data[0].originFileObj:"");
                        formData.append('descimgFile8',this.props.management.data[1]?this.props.management.data[1].originFileObj:"");
                        formData.append('descimgFile9',this.props.management.data[2]?this.props.management.data[2].originFileObj:"");
                        formData.append('descimgFile10',this.props.management.data[3]?this.props.management.data[3].originFileObj:"");
                        formData.append('descimgFile11',this.props.management.data[4]?this.props.management.data[4].originFileObj:"");


                    axios({
                        method:'post',
                        url:'/api/backstage/shop/uploadGoods',
                        header: {'Content-Type':'multipart/form-data'},
                        data:formData
                    }).then(res=>{

                        console.log(res)
                        //发布成功后的操作
                        if(res.data.code===200){
                            message.warning('发布成功');
                            this.props.history.push('/selling')
                        }else {
                            message.warning('发布失败');
                        }
                    })

                }else {
                    message.warning('请填写全部内容');
                }
            }else {
                message.warning('请上传相应数量的图片');
            }

        }else {
            message.warning('请勾选协议');
        }
    }

    render() {

        return(
            <div className="div_content">

                {/*基本信息*/}
                <div className="div_kuai">
                    <div className="title">基本信息</div>
                    <div className="jutiContent">
                        <div  className='div_inp'>
                            <span className="mingcheng"><span className="red_xing">*</span>商品名称：</span>
                            <Input placeholder="输入商品名称" onChange={this.shopName}/>
                        </div>
                        <div>
                            <span><span className="red_xing">*</span>商品图片(请上传6张图片)：</span>

                            <ImgCrop rotate>
                                <Tooltip placement="topLeft" title='请上传6张图片'>
                                    <Upload
                                        // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                        listType="picture-card"
                                        fileList={this.state.fileList}
                                        onChange={this.onChange}
                                        onPreview={this.onPreview}
                                        beforeUpload={this.beforeUploadMains}
                                    >
                                        {this.state.fileList.length < 6 && '+ 点击上传'}
                                    </Upload>
                                </Tooltip>
                            </ImgCrop>

                        </div>
                        <div>
                            <span><span className="red_xing">*</span>商品类别：</span>
                            <Cascader options={this.state.options} onChange={this.onChange2} placeholder="请选择" />
                        </div>
                    </div>
                </div>

                {/*价格设置*/}
                <div  className="div_kuai">
                    <div className="title">价格设置</div>
                    <div className="jutiContent">
                        <div className='div_inp'>
                            <span><span className="red_xing">*</span>售价：</span>
                            <InputNumber className='inp' min={1} max={10}  onChange={this.onChangeNum} />
                        </div>
                        <div className='div_inp'>
                            <span><span className="red_xing">*</span>市场价：</span>
                            <InputNumber min={1} max={10}  onChange={this.onChangeNum1} />
                        </div>
                        <div className='div_inp'>
                            <span><span className="red_xing">*</span>库存：</span>
                            <InputNumber className='inp' min={1} max={10}  onChange={this.onChangeNum2} />
                        </div>
                    </div>
                </div>

                {/*规格设置*/}
                <div  className="div_kuai">
                    <div className="title">规格设置</div>
                    <div className='div_inp jutiContent'>
                        <div className="guige"><span><span className="red_xing">*</span>尺寸：</span><Input placeholder="输入尺寸" onChange={this.size}/></div>
                        <div className="guige"><span><span className="red_xing">*</span>颜色：</span><Input placeholder="输入颜色" onChange={this.color}/></div>
                        <div className="guige"><span><span className="red_xing">*</span>品牌：</span><Input placeholder="输入品牌" onChange={this.brand}/></div>
                        <div className="guige"><span><span className="red_xing">*</span>产地：</span><Input placeholder="输入产地" onChange={this.place}/></div>
                    </div>
                </div>

                {/*商品详情*/}
                <div  className="div_kuai">
                    <div className="title">商品详情</div>
                    <div className="jutiContent">
                        <div className="kuozhan">支持扩展名：.jpg .jpeg .gif .png，图片大小不超过5M，共上传5张图片</div>
                        <div>
                            <Uploadpic/>

                        </div>
                    </div>
                </div>

                {/*底部按钮*/}
                <div className="publish_footer">
                    <Checkbox onChange={this.onChange3}>我已阅读并同意商品发布规范</Checkbox>
                    <Button type="primary" className="fabu" onClick={this.publish}>发布</Button>
                </div>

            </div>
        )
    }
}
export default PublishTwo